<template>
  <div class="comment-post">
    <!-- v-model.trim="message"  trim修饰符(顾名思义,删除首尾空格) -->
    <van-field
      class="post-field"
      v-model.trim="message"
      rows="2"
      autosize
      type="textarea"
      maxlength="50"
      placeholder="请输入留言"
      show-word-limit
    />
    <van-button
      class="post-btn"
      @click="onPost"
      :disabled="!message.length"
    >发布</van-button>
  </div>
</template>

<script>
import { addComment } from '@/api/comment.js'
// 事件中心
// import { emit } from '@/utils/eventHub.js'
export default {
  name: 'CommentPost',
  components: {},
  props: {
    target: {
      type: [Number, Object, String],
      required: true
    }
  },
  // 接收祖先元素的注入内容
  inject: {
    articleId: {
      type: [String, Number, Object],
      default: null
    }
  },
  data () {
    return {
      message: ''
    }
  },
  computed: {},
  watch: {},
  created () {},
  mounted () {},
  methods: {
    async onPost () {
      try {
        const { data: { data } } = await addComment({
          target: this.target.toString(),
          content: this.message,
          // 对文章作评论不传(对评论作评论再传)
          // art_id: this.articleId ? this.articleId.toString() : null
          art_id: (this.articleId == null || this.articleId.toString() === this.target.toString()) ? undefined : this.articleId.toString()
        })
        /* 方法1. 通过事件中心完成兄弟组件的数据交互 */
        // 通知兄弟(通过事件中心)添加数据到评论列表
        // emit('post-success', data)
        // 通知父亲
        // this.$emit('post-success')

        /* 方法2. 直接到父组件做相关操作 */
        this.$emit('post-success', data)

        // 清空内容
        this.message = ''
        this.$toast.success('发布成功!')
        // 关闭弹出层
      } catch (error) {
        // console.error(error)
        this.$toast.fail('发布评论失败!')
      }
    }
  }
}
</script>

<style scoped lang="less">
.comment-post {
  display: flex;
  align-items: center;
  padding: 32px 0 32px 32px;
  .post-field {
    background-color: #f5f7f9;
  }
  .post-btn {
    width: 150px;
    border: none;
    padding: 0;
    color: #6ba3d8;
    &::before {
      display: none;
    }
  }
}
</style>
